package io.github.wanggit.antcms.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.github.wanggit.antcms.server.domain.AntArticle;
import io.github.wanggit.antcms.server.domain.AntArticleMedia;
import io.github.wanggit.antcms.server.domain.AntMedia;
import io.github.wanggit.antcms.server.mapper.AntArticleMediaMapper;
import io.github.wanggit.antcms.server.service.ArticleMediaService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class ArticleMediaServiceImpl extends ServiceImpl<AntArticleMediaMapper, AntArticleMedia>
        implements ArticleMediaService {
    @Override
    public void saveOrUpdateRelations(List<AntMedia> medias, AntArticle antArticle) {
        QueryWrapper<AntArticleMedia> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", antArticle.getId());
        remove(queryWrapper);
        List<AntArticleMedia> articleMedias = new ArrayList<>();
        for (AntMedia media : medias) {
            AntArticleMedia articleMedia = new AntArticleMedia();
            articleMedia.setArticleId(antArticle.getId());
            articleMedia.setMediaId(media.getId());
            articleMedias.add(articleMedia);
        }
        saveBatch(articleMedias);
    }

    @Override
    public List<AntArticleMedia> findArticleMediaRelations(AntArticle article) {
        QueryWrapper<AntArticleMedia> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", article.getId());
        return list(queryWrapper);
    }

    @Override
    public void deleteRelationsByArticle(AntArticle article) {
        QueryWrapper<AntArticleMedia> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", article.getId());
        remove(queryWrapper);
    }
}
